package frame.security;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import frame.dao.DAO;
import frame.security.entity.User;

/**
 * shiro和应用的realm
 * @author MR.CUIPENG
 *
 */
public class MonitorRealm extends AuthorizingRealm{
	
	@Autowired
	private DAO dao;

	public MonitorRealm() {
		super();
	}
	
	/**
	 * 授权操作，决定那些角色可以使用那些资源
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
		String username = (String) super.getAvailablePrincipal(pc);  
		
		System.out.println("这个方法被执行了");
		
		List<String> permissions =dao.queryObjectList("permission", String.class, username);
		
//		List<String> perms=new ArrayList<String>(1);
//		perms.add(permissions.toString().replace("[", "").replace("]", "").replace(" ", ""));
		
		info.addStringPermissions(permissions);
		
		return info;
	}


	/**
	 * 认证操作，判断一个请求是否被允许进入系统
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		 SimpleAuthenticationInfo info = null;  
	      
	        String userId = token.getUsername(); 
	        String pwd=String.valueOf(token.getPassword());
	        User user=dao.queryObject("login",User.class, userId,pwd);
	        
	        info = new SimpleAuthenticationInfo(user.getUser_id(), user.getPassword(), getName()); 
	        
	        SecurityUtils.getSubject().getSession().setAttribute("current_user", user);
	        
	        return info;  
	}

}
